import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { ElMessage } from 'element-plus'

import router, { resetRoute } from '@/router'
import { useStore } from '@/store/user'
import { getToken ,removeToken } from '@/utils/auth'


export const PATH_URL: string =  import.meta.env.VITE_APP_BASE_API || 'http://ihrm-java.itheima.net' 
//console.log('代理公共路径',PATH_URL)
//console.log(import.meta.env)
// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL,
  timeout: 50000,
  //headers: { 'Content-Type': 'application/json' },
})

//添加请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const store=useStore()
    //console.log('store.token',store.token)
    if (store.token) {
      if (config.headers) {
        config.headers['Authorization'] = `Bearer ${ getToken() }`
      }
    }
    return config
  },
  (error: AxiosError) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res=response.data
    //*失败的提示
    if(!res.success){
      ElMessage({
        message: res.message || '失败',
        type: 'error',
        duration: 5 * 1000,
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
    //*成功的提示
    ElMessage({
      message: res.message || '成功',
      type: 'success',
      duration: 5 * 1000,
    })
    return res
  },
  (error: AxiosError) => {
    if (error.response?.status===401) {
      //清空数据
      useStore().$reset()
      //清空储存的token 
      removeToken()
      //跳转登录页
      router.push('/login')
      //重置路由
      resetRoute()
    }
    ElMessage({
      message:error.message,
      type:'error',
      duration:5*1000,
    })
    return Promise.reject(error)
  },
)

export default service